$(function () {
    //忽略大小写比较字符串是否相等
    String.prototype.equal = function (str) {

        if (str != undefined && str != null && this != undefined && this != null) {

            str = str.toLowerCase();
            var temp = this.toLowerCase();
            if (str == temp)
                return true;
            return false;
        }
        else
            return false;
    }


    var pDoc = $(parent.document);
    var pFrame = pDoc.find('#fieldFrame iframe');
    var currIndex = parseInt(pFrame.attr('data-current'));
    var pCurrent = pDoc.find('#fieldManage .table_form:[data-groupid="' + getGroupId() + '"] tbody > tr:eq(' + currIndex + ')');
    var pHidden = pCurrent.find('input:hidden'), currType = pCurrent.attr('data-type');

    var fieldNameList = new Array();
    initFieldNameList();
    //初始化fieldNameList
    function initFieldNameList() {
        pDoc.find("#fieldManage .table_form").find("tr input[name='fieldDomain']").each(function (i, n) {
            var valuestr = $(this).val()
            var valueJson = null;
            if (valuestr != undefined && valuestr != null && valuestr != "") {
                valueJson = JSON.parse(valuestr);
            }
            if (!$.isEmptyObject(valueJson)) {
                fieldNameList.push(valueJson);
            }
        });
    }

    function hasFieldName(str) {
        var flag = false;
        for (var i = 0; i < fieldNameList.length; i++) {
            if (fieldNameList[i].name.equal(str)) {
                flag = true;
            }
        }
        return flag;
    }







    var fieldData = {}
    var value = pHidden.val();

    var vCbox = $('#list_Validate :checkbox');

    //初始化
    if (value != null && value != "") {
        fieldData = JSON.parse(value);
        $('#fieldTitle').val(fieldData.remark);
        $('#fieldCode').val(fieldData.name);
        $('#fieldDefault').val(fieldData.value);
        $('#fieldTips').val(fieldData.tips);
        $('#fieldSize').val(fieldData.maxSize);
        $('#fieldEditerConfig').val(fieldData.entry);
        $('#fieldMeasurement').val(fieldData.unit);
        $.post('/m/common/getFieldFilters', function (data) {
            var filterHtml = "";
            for (var f = 0; f < data.length; f++) {
                var fvalue = data[f].FilterName;
                if (fieldData.filter!=undefined&&fieldData.filter.indexOf(fvalue) != -1) {
                    filterHtml += '<li><label><input type="checkbox" checked value="' + fvalue + '" /></label>' + fvalue + '</li>';
                } else {
                    filterHtml += '<li><label><input type="checkbox" value="' + fvalue + '" /></label>' + fvalue + '</li>';
                }
                
            }
            $('#list_filter').html(filterHtml);
        });
        if (fieldData.validate != '{}') {
            var intVdcbx = new Array();
            intVdcbx = fieldData.validate.replace(/{|}/g, '').split(/,(?!\d+])/g);
            $.each(vCbox, function (i, n) {
                for (var ii in intVdcbx) {
                    var patt = new RegExp(intVdcbx[ii].split(':')[0] + ':');
                    if (patt.test($(n).val())) {
                        $(n).attr('checked', true);
                        if ($(n).attr('data-input') == '1') {
                            $(n).parents('li').find(':text').removeAttr('disabled');
                        }
                    }
                }
            });
        }

        if (fieldData.type!="12"&fieldData.entry != undefined) {
            var inputType = 'radio', inputChecked = '', ischecked = 'data-checked="0"';
            if (fieldData.type == "5") inputType = 'checkbox';
            var optionHtml = '', optionDefault = fieldData.value.split(',');
            for (var i in fieldData.entry) {
                for (var ii in optionDefault) {
                    if (optionDefault[ii] == fieldData.entry[i].entryValue) {
                        inputChecked = 'checked="checked"';
                        ischecked = 'data-checked="1"';
                    }
                }
                optionHtml += '<li><a class="ico ico_reduce" title="删除"></a><a class="ico ico_fildadd" title="添加"></a><input ' + inputChecked + ' ' + ischecked + ' class="radio" type="' + inputType + '" /><input style="width:60px;" class="text" type="text" value="' + fieldData.entry[i].entryName + '" /><span>=></span><input style="width:60px;" class="text" type="text" value="' + fieldData.entry[i].entryValue + '" /></li>';
                inputChecked = ''; ischecked = 'data-checked="0"';
            }
            $('#list_option').html(optionHtml);
        }
        if (fieldData.type == "12") {
            var dataHtml = '';
            $.post("/m/common/GetPrototypes/", function (data) {
                for (var j = 0; j < data.length; j++) {
                    if (fieldData.value == data[j].Id) {
                        dataHtml += "<option selected='selected' value='" + data[j].Id + "'>" + data[j].Title + "</option>";
                    } else {
                        dataHtml += "<option value='" + data[j].Id + "'>" + data[j].Title + "</option>";
                    }
                }
                $('#list_option select[name="Prototype"]').html(dataHtml);
                fieldData.value = $('#list_option select[name="Prototype"]').val();
                pHidden.val(JSON.stringify(fieldData));
            });
            if (fieldData.unit == "无限制") {
                $('#unlimited').attr("checked", "checked");
                var $_unit = $('#unlimited').parent().prev();
                $_unit.attr("disabled", "disabled");
                $_unit.val("");
            }
        }
        if (fieldData.type=="19") {
            var $type = $('.list_option select[name="type"]');
            $type.val(fieldData.value);
        }
    }



    //修改
    $('#fieldTitle').change(function () {
        var v = $(this).val();
        pCurrent.children('th').find("span").text(v);
        fieldData.remark = v;
        pHidden.val(JSON.stringify(fieldData));
    });
    $('#fieldCode').change(function () {
        var v = $(this).val();
        if (hasFieldName(v)) {
            alert("该原型中已经包含含有这个字段代码的字段！");
        }
        else {
            fieldData.name = v;
            pHidden.val(JSON.stringify(fieldData));
        }
    });
    $('#fieldMeasurement').change(function () {
        var v = $(this).val();
        fieldData.unit = v;
        pHidden.val(JSON.stringify(fieldData));
    });
    $('#fieldDefault').change(function () {
        var v = $(this).val();
        pCurrent.find(':text').val(v);
        pCurrent.find(':password').val(v);
        pCurrent.find('textarea').val(v);
        fieldData.value = v;
        pHidden.val(JSON.stringify(fieldData));
    });
    $('#fieldTips').change(function () {
        var v = $(this).val();
        fieldData.tips = v;
        pHidden.val(JSON.stringify(fieldData));
    });
    $('#addValidate').click(function () {
        $(this).hide().prev().css({ 'height': 'auto', 'overflow': 'visible' });
        parentHeight();
    });
    $('#fieldSize').change(function () {
        var v = $(this).val();
        fieldData.maxSize = v;
        pHidden.val(JSON.stringify(fieldData));
    });
    $('#fieldEditerConfig').change(function () {
        var v = $(this).val();
        fieldData.entry = v;
        pHidden.val(JSON.stringify(fieldData));
    });
    $('#list_option select').live("change", function () {
        fieldData.value = $(this).val();
        fieldData.entry = $(this).find('option:selected').text();
        pHidden.val(JSON.stringify(fieldData));
    });
    $('.list_option select').live("change", function () {
        fieldData.value = $(this).val();
        pHidden.val(JSON.stringify(fieldData));
    });
    $('#unlimited').click(function () {
        var $this = $(this);
        var $unit = $this.parent().prev();
        if ($this.attr("checked") == "checked") {
            $unit.attr("disabled", "disabled");
            $unit.val("");
            fieldData.unit = "无限制";
        } else {
            $unit.removeAttr("disabled");
            $unit.val("1");
            fieldData.unit = "1";
        }
        pHidden.val(JSON.stringify(fieldData));
    });
    $('#list_option select[Name="Prototype"]').live("change", function () {
        var $this = $(this);
        var $parent = $(this).parents("#list_option");
        $.post("/m/common/GetCategories", { prototypeId: $this.val() }, function (data) {
            var shtml = '<option value="0">请选择</option>';
            for (var j = 0; j < data.length; j++) {
                shtml += "<option value='" + data[j].Id + "'>" + data[j].Title + "</option>";
            }
            $parent.find('select[name="Category"]').html(shtml);
        });
        $.post("/m/common/GetTags", { prototypeId: $this.val() }, function (data) {
            var shtml = '<option value="0">请选择</option>';
            for (var j = 0; j < data.length; j++) {
                shtml += "<option value='" + data[j].Id + "'>" + data[j].Title + "</option>";
            }
            $parent.find('select[name="Tag"]').html(shtml);
        });

    });
    $('#list_filter input:checkbox').live("click", function() {
        var filter = new Array();
        $('#list_filter input:checked').each(function (i, n) {
            filter.push($(n).val());
        });
        fieldData.filter = filter.join(',');
        pHidden.val(JSON.stringify(fieldData));
    });
    //验证规则

    vCbox.click(function () {
        fieldData.validate = vCboxVal();
        pHidden.val(JSON.stringify(fieldData));
        if ($(this).attr('data-input') == '1') {
            if ($(this).is(':checked')) {
                $(this).parents('li').find(':text').removeAttr('disabled');
            } else {
                $(this).parents('li').find(':text').attr('disabled', 'disabled');
            }
        }
    });
    $('#list_Validate :text').change(function () {
        var cboxVal = $(this).parent('li').find(':checkbox');
        cboxVal.val(cboxVal.val().split(':')[0] + ':' + $(this).val());
        fieldData.validate = vCboxVal();
        pHidden.val(JSON.stringify(fieldData));
    });
    function vCboxVal() {
        var valArray = new Array();
        $.each(vCbox, function (i, n) {
            if ($(n).is(':checked')) {
                valArray.push($(n).val());
            }
        });
        return '{' + valArray.join(',') + '}';
    }

    //选项类型操作
    $('#list_option :radio').live('click', function () {
        if ($(this).attr('data-checked') == '1') {
            $(this).attr('data-checked', 0)
            $(this).removeAttr('checked');
            fieldData.value = '';
        } else {
            $(this).attr('data-checked', 1);
            $(this).parent('li').siblings().children(':radio').removeAttr('checked').attr('data-checked', 0);
            fieldData.value = $(this).siblings(':text:last').val();
        }
        pHidden.val(JSON.stringify(fieldData));
        if (fieldData.type != '6') {
            $.each(pCurrent.find(':radio'), function () {
                $(this).removeAttr('checked');
                if ($(this).val() == fieldData.value) $(this).attr('checked', true);
            });
        } else {
            pCurrent.find('option').val(fieldData.value).text($(this).next().val());
        }
    });
    var optionCbox = $('#list_option :checkbox');
    optionCbox.live('click', function () {
        var arrCbox = new Array();
        $.each(optionCbox, function () {
            if ($(this).is(':checked')) {
                arrCbox.push($(this).siblings(':text:last').val());
            }
        });
        fieldData.value = arrCbox.join(',');
        pHidden.val(JSON.stringify(fieldData));
        $.each(pCurrent.find(':checkbox'), function () {
            $(this).removeAttr('checked');
            for (var i in arrCbox) {
                if ($(this).val() == arrCbox[i]) $(this).attr('checked', true);
            }
        });
    });
    $('#list_option :text').live('change', function () {
        var optVal = $(this).val(), optIndex = $(this).parent().index();
        if ($(this).next().text() == '=>') {
            fieldData.entry[optIndex].entryName = optVal;
            if (fieldData.type != '6') {
                pCurrent.find('label:eq(' + optIndex + ') > span').text(optVal);
            } else {
                if ($(this).siblings(':radio').attr('data-checked') == '1')
                    pCurrent.find('option').text(optVal);
            }
        } else {
            fieldData.entry[optIndex].entryValue = optVal;
            fieldData.value = optVal;
            if (fieldData.type != '6') {
                pCurrent.find('label:eq(' + optIndex + ') > input').val(optVal);
            } else {
                if ($(this).siblings(':radio').attr('data-checked') == '1')
                    pCurrent.find('option').val(optVal);
            }
        }
        pHidden.val(JSON.stringify(fieldData));

    });
    $('#list_option a.ico_reduce').live('click', function () {
        var optIndex = $(this).parent().index();
        (fieldData.entry).splice(optIndex, 1);

        if (fieldData.type != '6') {
            pCurrent.find('label:eq(' + optIndex + ')').remove();
        } else {
            pCurrent.find('option').val('').text('');
        }
        if (fieldData.type != '5') {
            if ($(this).siblings(':radio').attr('data-checked') == '1') fieldData.value = '';
        } else {
            if ($(this).siblings(':checkbox').is(':checked')) {
                var newOptVal = fieldData.value.split(',');
                newOptVal.splice(optIndex, 1);
                fieldData.value = newOptVal.join(',');
            }
        }
        pHidden.val(JSON.stringify(fieldData));
        $(this).parent().remove();
    });
    $('#list_option a.ico_fildadd').live('click', function () {
        var optIndex = $(this).parent().index();
        fieldData.entry.splice(optIndex + 1, 0, { "entryName": "选项", "entryValue": "Default" });
        $(this).parent().after('<li><a class="ico ico_reduce" title="删除"></a><a class="ico ico_fildadd" title="添加"></a><input class="radio" type="' + inputType + '" /><input style="width:60px;" class="text" type="text" value="选项" /><span>=></span><input style="width:60px;" class="text" type="text" value="Default" /></li>');
        if (fieldData.type != '6') {
            pCurrent.find('label:eq(' + optIndex + ')').after('<label class="mr_2"><input class="' + inputType + '" disabled="disabled" type="' + inputType + '" value="Default"><span>选项</span></label>');
        }
        pHidden.val(JSON.stringify(fieldData));
        parentHeight();
    });


    //切换类型
    var timing;
    $('#fieldChange').bind({
        'click': function () { $(this).next().slideDown(); },
        'mouseout': function () {
            var ts = $(this); timing = setTimeout(function () { ts.next().hide(); }, 150);
        }
    });
    $('#fieldChange + ul').bind({
        'mouseover': function () { clearTimeout(timing); },
        'mouseout': function () {
            var ts = $(this); timing = setTimeout(function () { ts.hide(); }, 150);
        }
    });
    $('#fieldChange + ul > li').click(function () {
        var tType = $(this).attr('data-type');
        $(this).parent().hide();
        if (currType != tType) {
            var pManage = pDoc.find('#fieldManage');
            pManage.attr("oldData", JSON.stringify(fieldData));
            pCurrent.remove();
            pDoc.find('#addField  ul  li[data-type="' + tType + '"]').attr('data-insert', currIndex - 1).trigger("click");
        }
    });


    //父窗口高度
    parentHeight();
    function parentHeight() {
        pDoc.find('#fieldManage').css("min-height", 0);
        var iframeHeight = $('#fieldWrap').height() - 90;
        var scanHeight = pDoc.find('#fieldManage').height();
        var h = iframeHeight >= scanHeight ? iframeHeight : scanHeight;
        if (h <= 380) {
            pDoc.find('#fieldManage').animate({ 'min-height': 380 }, 0);
            pFrame.animate({ 'min-height': 450 }, 0);
        }
        else {
            pDoc.find('#fieldManage').delay(100).animate({ 'min-height': h }, 0);
            pFrame.animate({ 'min-height': h + 90 }, 0);
        }
    }


    function getGroupId() {
        return pDoc.find(".js_field_tab").find("a.current").attr("data-groupId");
    }
});